<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2019/11/9
 * Time: 20:24
 */
class ctrl_pdd_mq extends L {

    /**
     * 描述 ：下载阿里的图片到本地
     * 参数 ：{
     *      data ：{
     *          productId : ali的产品Id
     *          account : 刊登账号
     *      }
     * }
     * 作者 ：Zoro.Zhu
    **/
    public static function downloadImg($params = null){
        set_time_limit(0);
        $productId = !empty($params['data']['productId']) ? $params['data']['productId'] : $_GET['pro'];
        $account = !empty($params['data']['account']) ? $params['data']['account'] : $_GET['acc'];
        $productInfo = model_aliProduct::getProductInfo($productId);
//        p(model_aliProduct::getImg(array('productId' => $productId)));
        if(!model_aliProduct::getImg(array('productId' => $productId))){
            $vsPath = serv_rapi_ali::downloadImage($productInfo);
            $productInfo['vsPath'] = $vsPath;
        }
        core_base::trans(null);
//        p($productInfo);
        if(is_array($productInfo['vsPath'])){
            core_ali::setProduct($productInfo, $account);
        }
        $result = core_base::trans(true);
//        p($result);
        if($result['state']){
            //没有下载到图片，不继续往下执行
            if(is_array($productInfo['vsPath'])){
                $sql = "UPDATE `ali_product` 
                SET 
                    `state` = 30 
                WHERE
                    `productId` = '{$productId}'";
                L::sql($sql);
                //设置上传图片到pdd的消息队列，上传图片后再进行刊登到pdd
                of_base_com_mq::set(array('pddImgUpload', $productId), array('productId' => $productId, 'account' => $account));
            }else{
                $errorInfo = [
                    'info' => $productInfo['vsPath'],
                    'date' => date('Y-m-d H:i:s')
                ];
                $sql = "UPDATE `ali_product` 
                SET 
                    `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                    `state` = 25 
                WHERE
                    `productId` = '{$productId}'";
                L::sql($sql);
            }
            return true;
        }
        return false;
    }

    /**
     * 描述 ：上传图片到pdd，结束后再触发刊登的消息队列
     * 参数 ：{
     *      data ：{
     *          productId : 产品Id
     *          account : 销售店铺
     *      }
     * }
     * 作者 ：Zoro.Zhu
    **/
    public static function pddImgUpload($params = null){
        set_time_limit(0);
        $params['productId'] = !empty($params['data']['productId']) ? $params['data']['productId'] : $_GET['pro'];
        $params['account'] = !empty($params['data']['account']) ? $params['data']['account'] : $_GET['acc'];
        $params['isPddUrl'] = false;
        $info = model_aliProduct::getImg($params);
//        p($info);
        $token = model_vsAccount::getAccountToken(['account' => $params['account']]);
        $data['accessToken'] = $token['accessToken'];
        $data['clientId'] = $token['appKey'];
        $data['clientSecret'] = $token['appSecret'];
        $error = [];
        foreach($info as $val){
            $path = of::config('_of.rootDir') . $val['vsPath'];
            $data['image'] = model_com::base64EncodeImage($path);
            $res = model_api_pdd::imageUpload($data);
            if(!empty($res['image_url'])){
                core_base::trans(null);
                core_ali::updProductImg(array(
                    'productId' => $val['productId'],
                    'vsPath' => $val['vsPath'],
                    'pddUrl' => $res['image_url'],
                ));
                $res = core_base::trans(true);
                if(!$res['state']){
                    $error[] = join(',' , $res['data']);
                    break;
                }
            }else if(!empty($res['error_msg'])){
                //含有二维码的图片，跳过
                if($res['error_msg'] == '您的图片中含有二维码，请您重新上传'){
                    continue;
                }else{
                    $error[] = $res['error_msg'];
                    break;
                }
            }else{
                $error[] = '未知错误请重试';
                break;
            }
        }
        if(!empty($error)){
            $errorInfo = [
                'info' => join(',', $error),
                'date' => date('Y-m-d H:i:s')
            ];
            $sql = "UPDATE `ali_product` 
            SET 
                `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                `state` = 35 
            WHERE
                `productId` = '{$params['productId']}'";
            L::sql($sql);
        } else {
            $sql = "UPDATE `ali_product` 
            SET 
                `state` = 40 
            WHERE
                `productId` = '{$params['productId']}'";
            L::sql($sql);
            of_base_com_mq::set(['pddProductAdd', $params['productId']], ['productId' => $params['productId'], 'account' => $params['account']]);
        }
        return true;
    }


    /**
     * 描述 ：刊登产品到平台
     * 参数 ：{
     *      data ：{
     *          productId : 产品Id
     *          account : 店铺名称
     *      }
     * }
     * 作者 ：Zoro.Zhu
     **/
    public static function pddProductAdd($params = null) {
        core_base::trans(null);
        $productId = !empty($params['data']['productId']) ? $params['data']['productId'] : $_GET['pro'];
        $account = !empty($params['data']['account']) ? $params['data']['account'] : $_GET['acc'];
        $proInfo = model_aliProduct::getProductInfo($productId);
        $token = model_vsAccount::getAccountToken(['account' => $account]);
        $data = self::getPddProductData($proInfo,$token);
        $goods = model_api_pdd::productAdd($data);
        if(!empty($goods['goods_id'])){
            $sql = "UPDATE `ali_product` 
            SET 
                `pddId` = '{$goods['goods_id']}',
                `state` = 50 
            WHERE
                `productId` = '{$productId}'";
            L::sql($sql);
        }else{
            $errorInfo = [
                'info' => $goods['error_msg'],
                'date' => date('Y-m-d H:i:s')
            ];
            $sql = "UPDATE `ali_product` 
            SET 
                `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                `state` = 45 
            WHERE
                `productId` = '{$productId}'";
            L::sql($sql);
        }
        $res = core_base::trans(true);
        if($res['state'] && !empty($goods)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 描述 ：整理SKU数据
     * 参数 ：{
     *      sku_list : sku列表
     * }
     * 作者 ：Zoro.Zhu
    **/
    public static function skuInfo($skuList, $imgUrl, $price, $account, $weight){
        $attr = $skuData = [];
        //整理属性数据
        $img = [];
        foreach($skuList as $row){
            foreach($row['attributes'] as $key => $r){
                !empty($r['skuImageUrl']) && $img[$r['skuImageUrl']] = 1;
                $attr[$key][] = $r['attributeValue'];
            }
        }
        $imgKey = array_flip(array_keys($img));
        $specInfo = self::getAttrSpec($attr, $account);
        //开始拼装sku列表
        foreach($skuList as $key => $sku){
            $isOnsale = $sku['amountOnSale'] < 10 ? 0 : 1;
            $price = !empty($sku['price']) ? $sku['price'] : $price;
            $priceSku = self::shopPrice($price);
            $spec = [];
            $oldCat = '';
            $skuImageUrl = '';
            foreach($sku['attributes'] as $k => $r){
                //属性为空，不上传
                if(empty($specInfo[$k][$r['attributeValue']])){
                    continue 2;
                }
                if($oldCat != '' && $oldCat == $r['attributeValue']){
                    continue;
                }
                !empty($r['skuImageUrl']) && $skuImageUrl = $r['skuImageUrl'];
                $oldCat = $r['attributeValue'];
                $spec[] = $specInfo[$k][$r['attributeValue']];
            }
            $thumbUrl = !empty($skuImageUrl) ? $imgUrl[30][$imgKey[$skuImageUrl]] : (!empty($imgUrl[10]) ? current($imgUrl[10]) : '');

            $skuData[] = [
                'thumb_url' => $thumbUrl,                                       //SKU图片
                'spec_id_list' => json_encode($spec),
                'weight' => $weight,
                'quantity' => ceil($sku['amountOnSale'] / 10),              //商品sku库存初始数量
                'limit_quantity' => 10,                                          //sku购买限制，只入参999
                'is_onsale' =>  $isOnsale,                                       //sku上架状态，0-已下架，1-上架中
                'out_sku_sn' => 'VS' . $sku['skuId'],                               //商品sku外部编码
                'multi_price' => ceil($priceSku * 100),                                    //商品团购价格
                'price' => ceil($priceSku * 1.1 * 100) + 100,                                    //商品单买价格
            ];
        }
        return json_encode($skuData);
    }

    /**
     * 描述 ：获取属性对应的specId
     * 参数 ：[
     *      属性名称,....
     * ]
     * 返回值 ：{
     *      attrName 属性名称 ：specId
     * }
     * 作者 ：Zoro.Zhu
    **/
    public static function getAttrSpec($attrs, $account){
        $token = model_vsAccount::getAccountToken(['account' => $account]);
        $data['accessToken'] = $token['accessToken'];
        $data['clientId'] = $token['appKey'];
        $data['clientSecret'] = $token['appSecret'];
        $attrSpec = [];
        foreach($attrs as $z => $attr){
            $attrInfo = model_aliProduct::getProductAttr($attr);
            $upAttr = [];
            foreach($attrInfo as $row){
                $attrSpec[$z][$row['attrVal']] = $row['pddSpecId'];
            }
            //梳理一遍属性
            foreach ($attr as $a){
                //如果pddSpecId为空，就重新获取一下
                if(empty($attrSpec[$z][$a])){
                    $attrSpecList = serv_rapi_pdd::getAttrSpec($account);
                    $data['parent_spec_id'] = $attrSpecList[$z]['parent_spec_id'];
                    $data['spec_name'] = $a;
                    $info = model_api_pdd::getSpec($data);
                    if($info !== false){
                        $attrSpec[$z][$a] = $info['spec_id'];
                        $upAttr[$a] = $info['spec_id'];
                    }
                }
            }
            if(!empty($upAttr)){
                core_ali::updAttrSpec($upAttr);
            }
        }
        return $attrSpec;
    }

    /**
     * 描述 ：计算售价
     * 作者 ：Zoro.Zhu
     **/
    public static function shopPrice($price) {
        $shopPrice = model_com::getVsConfig('shopPrice');
        $salePrice = 0;
        foreach ($shopPrice as $key => $val) {
            $section = explode('~~', $key);
            $alg = explode('~~', $val);
            if($price >= $section[0] && $price < $section[1]){
                $salePrice = $price;
                foreach($alg as $a){
                    if(substr($a, 0, 1) == '+'){
                        $salePrice = bcadd($salePrice, substr($a, 1), 2);
                    }elseif (substr($a, 0, 1) == '*'){
                        $salePrice = bcmul($salePrice, substr($a, 1), 2);
                    }
                }
            }
        }
        $price = explode('.', $salePrice);
        $salePrice = $price[0] . '.98';
        return $salePrice;
    }

    /**
     * 描述 ：获取拼多多预测的类目ID
     * 作者 ：Zoro.Zhu
    **/
    public static function mappingCatId($params){
        $data['accessToken'] = $params['accessToken'];
        $data['clientId'] = $params['clientId'];
        $data['clientSecret'] = $params['clientSecret'];
        $data['catId'] = $params['catId'];
        $data['catName'] = $params['catName'];
        $data['productName'] = $params['goods_name'];
        $res = model_api_pdd::mappingCat($data);
        if(!empty($res)){
            return !empty($res['cat_id4']) ? $res['cat_id4'] : $res['cat_id3'];
        }
        return false;
    }

    /**
     * 描述 ：根据ali的类目获取pdd的类目ID
     * 参数 ：$aliCatName ：ali的类目名称
     * 返回值 ：$pddCatId ：pdd的类目ID
     * 作者 ：Zoro.Zhu
    **/
    public static function getCatId($aliCatName){
        //首先拆分根据“、”拆分
        $catAy = explode("、", $aliCatName);
        foreach($catAy as $catName){
            if(strlen($catName) > 9){
                $catName = mb_substr($catName, -3, 3, 'utf-8');
            }
            if($catId = model_pddCat::getCatId($catName)){
                //校验一下该ID有没有子ID，有的话返回第一个子ID
                $catId = model_pddCat::getSonCatId($catId);
                return $catId;
            }
        }
        //三个字没匹配到，就两个字匹配
        foreach($catAy as $catName){
            if(strlen($catName) > 6){
                $catName = mb_substr($catName, -2, 2, 'utf-8');
            }
            if($catId = model_pddCat::getCatId($catName)){
                //校验一下该ID有没有子ID，有的话返回第一个子ID
                $catId = model_pddCat::getSonCatId($catId);
                return $catId;
            }
        }
        //两个字没匹配到，就一个字匹配
        foreach($catAy as $catName){
            if(strlen($catName) > 3){
                $catName = mb_substr($catName, -1, 1, 'utf-8');
            }
            if($catId = model_pddCat::getCatId($catName)){
                //校验一下该ID有没有子ID，有的话返回第一个子ID
                $catId = model_pddCat::getSonCatId($catId);
                return $catId;
            }
        }
        //没匹配到怎么办,暂时先写死，口红
        return 18496;
    }


    /**
     * 描述 ：抓取pdd订单
     * 参数 ：{
     *      data ：{
     *          account : 账号
     *      }
     * }
     * 作者 ：Zoro.Zhu
    **/
    public static function getOrderList($params = null){
        core_base::trans(null);
        $account = !empty($params['data']['account']) ? $params['data']['account'] : $_GET['acc'];
        $page = !empty($params['data']['page']) ? $params['data']['page'] : 1;
        $stateTime = !empty($params['data']['stateTime']) ? $params['data']['stateTime'] : strtotime(date('Y-m-d', time() - 86400*3));             //上次抓单时间
        $endTime = !empty($params['data']['endTime']) ? $params['data']['endTime'] : $stateTime + 86400;
        $token = empty($params['data']['token']) ? model_vsAccount::getAccountToken(['account' => $account]) : $params['data']['token'];

        $data['accessToken'] = $token['accessToken'];
        $data['clientId'] = $token['appKey'];
        $data['clientSecret'] = $token['appSecret'];
        $data['page'] = $page;
        $data['stateDate'] = $stateTime;
        $data['endDate'] = $endTime;
        $orderList = model_api_pdd::getOrderList($data);
        p($orderList);
        if(!empty($orderList['order_list'])){
            foreach($orderList['order_list'] as $row){
                core_pdd::setOrder($row, $account);                                                      //记录订单
            }
        }
        $res = core_base::trans(true);
        if($res['state'] && isset($orderList['total_count'])){
            if($orderList['total_count'] > ($page * 100)){
                return self::getOrderList(['data' => [
                    'account' => $account,
                    'page' => $page + 1,
                    'stateTime' => $stateTime,
                    'endTime' => $endTime,
                    'token' => $token
                ]]);
            }else{
                if($page == 1){
                    //设置一个消息队列，一个小时之后，继续抓单
                    of_base_com_mq::set(['getPddOrder', $account, 3600], ['account' => $account, 'stateTime' => $endTime]);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 描述 ：上传物流单号到pdd
     * 参数 ：{
     *      data ：{
     *          orderId : 阿里巴巴订单号
     *      }
     * }
     * 作者 ：Zoro.Zhu
     **/
    public static function orderSend($params = null){
        $aliOrder = !empty($params['data']['orderId']) ? $params['data']['orderId'] : $_GET['orderId'];
//        $pddOrder = !empty($params['data']['pddOrder']) ? $params['data']['pddOrder'] : $_GET['pddOrder'];
        $orderData = model_order::getOrder(['aliOrder' => $aliOrder]);
        $token = model_vsAccount::getAccountToken(['account' => $orderData[0]['accountPdd']]);
        $aliData = json_decode($orderData[0]['aliData'], true);
        $logisticsInfo = $aliData['nativeLogistics']['logisticsItems'][0];
        $data['accessToken'] = $token['accessToken'];
        $data['clientId'] = $token['appKey'];
        $data['clientSecret'] = $token['appSecret'];
        $data['order_sn'] = $orderData[0]['pddOrder'];
        $logisticsList = model_pddLogistics::getList();
        $logisticsNameList = model_pddLogistics::getListName();
        $data['logistics_id'] = !empty($logisticsList[$logisticsInfo['logisticsCompanyNo']]) ? $logisticsList[$logisticsInfo['logisticsCompanyNo']] : $logisticsNameList[$logisticsInfo['logisticsCompanyName']];
        $data['tracking_number'] = $logisticsInfo['logisticsBillNo'];
        $res = model_api_pdd::orderSend($data);
        if(!empty($res['is_success'])){
            L::sql("UPDATE `pdd_order` 
            SET `orderState` = '50' 
            WHERE
                `aliOrder` = '{$aliOrder}'");
            return true;
        }
        return 600;
    }

    /**
     * 描述 ：获取类目的商品属性信息
     * 作者 ：Zoro.Zhu
    **/
    public static function getCatInfo($params){
        $catAttr = model_pddCat::getAttr($params['cat_id']);
        $properties = [];
        if(empty($catAttr)){
            $catAttr = model_api_pdd::getCatTemp($params);
            if(!empty($catAttr)){
                model_pddCat::insertCatAttr($catAttr, $params['cat_id']);
            }
        }else{
            $catAttr = json_decode($catAttr[0]['catData'], true);
        }
        if(empty($catAttr)){
            return $properties;
        }
        $penId = [];
        foreach($catAttr['properties'] as $row){
            if(!empty($row['is_sale'])){
                continue;
            }
            $penId[] = $row['values'][0]['vid'];
            $vid = $row['values'][0]['vid'];
            if(!empty($row['values'][0]['parent_vids'])){
                foreach ($row['values'] as $parent){
                    foreach($parent['parent_vids'] as $pa){
                        if(in_array($pa, $penId)){
                            $vid = $parent['vid'];
                            continue 2;
                        }
                    }
                }
            }
            !empty($row['values'][0]['vid']) && $properties[] = [
                'template_pid' => $row['id'],
                'vid' => $vid,
            ];
        }
        return $properties;
    }

    /**
     * 描述 ：修改产品信息
     * 参数 ：{
     *      data ：{
     *          productId : ali的产品Id
     *          account : 店铺名称
     *      }
     * }
     * 作者 ：Zoro.Zhu
     **/
    public static function pddProductUpd($params = null){
        core_base::trans(null);
        $productId = !empty($params['data']['productId']) ? $params['data']['productId'] : $_GET['pro'];
        $account = !empty($params['data']['account']) ? $params['data']['account'] : $_GET['acc'];
        $proInfo = model_aliProduct::getProductInfo($productId);
        $token = model_vsAccount::getAccountToken(['account' => $account]);
        $data = self::getPddProductData($proInfo,$token);
        $goods = model_api_pdd::productUpd($data);
        p($goods);
        if(!empty($goods['is_success'])){
            $res = core_base::trans(true);
            if($res['state'] && !empty($goods)){
                return true;
            }else{
                return false;
            }
        }elseif(!empty($goods['error_msg']) && $goods['error_msg'] == '商品不存在'){
            $errorInfo = [
                'info' => $goods['error_msg'],
                'date' => date('Y-m-d H:i:s')
            ];
            $sql = "UPDATE `ali_product` 
            SET 
                `errorData` = '" . addslashes(json_encode($errorInfo)) . "',
                `state` = 70 
            WHERE
                `productId` = '{$productId}'";
            L::sql($sql);
            $res = core_base::trans(true);
            if($res['state'] && !empty($goods)){
                return true;
            }else{
                return false;
            }
        }else{
            core_base::trans(false);
            return 86400;
        }
    }

    /**
     * 描述 ：将ali的产品数据，转换为pdd的产品数据
     * 参数1 ：ali的产品数据
     * 参数2 ：pdd的token信息
     * 作者 ：Zoro.Zhu
    **/
    public static function getPddProductData($proInfo,$token){
        $data['account'] = $token['account'];
        $data['accessToken'] = $token['accessToken'];
        $data['clientId'] = $token['appKey'];
        $data['clientSecret'] = $token['appSecret'];
        //运费模板Id
        $logisticsTempId = model_api_pdd::getLogisticsTemp($data);
        //产品标题
        $data['goods_name'] = $proInfo['productInfo']['subject'];
        $data['goods_id'] = $proInfo['pddId'];
        //类目
        $data['catId'] = $proInfo['productInfo']['categoryID'];
        $data['catName'] = $proInfo['productInfo']['categoryName'];
        //调用拼多多接口进行预测类目ID
        $catId = self::mappingCatId($data);
        $data['cat_id'] = !empty($catId) ? $catId : self::getCatId($proInfo['productInfo']['categoryName']);//叶子类目ID
        //        echo $data['cat_id'];
        //获取类目属性信息
        $data['goods_properties'] = json_encode(self::getCatInfo($data));
        //图片
        $imgInfo = model_aliProduct::getImg(['productId' => $proInfo['productInfo']['productID'],'isPddUrl' => true]);
        $mainImg = $imgUrl = [];
        $imgI = 0;
        foreach($imgInfo as $val){
            $imgUrl[$val['type']][] = $val['pddUrl'];
            //轮播图
            if($val['type'] != 20 && $imgI < 10){
                $imgI ++;
                $mainImg[] = $val['pddUrl'];
            }
        }
        $data['carousel_gallery'] = !empty($mainImg) ? json_encode($mainImg) : '[]';
        $data['detail_gallery'] = !empty($imgUrl[20]) ? json_encode($imgUrl[20]) : $data['carousel_gallery'];
        //运费模板
        $data['cost_template_id'] = $logisticsTempId[0]['template_id'];
        //价格
        $price = 0;
        foreach ($proInfo['productInfo']['saleInfo']['priceRanges'] as $row){
            if($row['price'] > $price){
                $price = $row['price'];
            }
        }
        foreach ($proInfo['productInfo']['skuInfos'] as $row){
            if(!empty($row['price']) && $row['price'] > $price){
                $price = $row['price'];
            }
        }
        //取到最高价，然后翻三倍作为市场价，但是价格为0时，就直接退出
        if($price == 0){
            return '价格为0！';
        }
        $marketPrice = self::shopPrice($price);
        $data['market_price'] = ceil($marketPrice * 3 * 100);             //市场价（分）
        $data['shipment_limit_second'] = 3600 * 48;                             //承诺发货时间（ 秒）

        //描述
        $data['goods_desc'] = $proInfo['productInfo']['subject'];               //商品描述， 字数限制：20-500
        $data['tiny_name'] = mb_substr($proInfo['productInfo']['subject'], -10, 10, 'utf-8'); //短标题 字数，10个汉字
        $data['goods_type'] = '1';                                              //1-国内普通商品，2-海外进口，3-保税仓BC直供，4-海外BC直邮 ,5-流量,6-话费,7,优惠券;8-QQ充值,9-加油卡,18-海外CC个人行邮
        $data['country_id'] = '0';                                              //国家或地区ID
        !empty($proInfo['productInfo']['mainVedio']) && $data['carousel_video_url'] = $proInfo['productInfo']['mainVedio'];
        $weight = !empty($proInfo['productInfo']['shippingInfo']['unitWeight']) ?
            $proInfo['productInfo']['shippingInfo']['unitWeight'] * 1000 : 0;
        $data['sku_list'] = self::skuInfo($proInfo['productInfo']['skuInfos'], $imgUrl, $price, $token['account'], $weight);        //sku列表
        return $data;
    }


}
return true;